package com.cnebula.uas.sso.controller;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cnebula.uas.sso.ConfAdmin;
import com.cnebula.uas.sso.model.ErrorInfo;
import com.cnebula.uas.sso.model.SSOToken;
import com.cnebula.uas.sso.service.AuthTokenService;
import com.cnebula.uas.sso.service.TenantManService;

@Controller
@RequestMapping(value = "/uas/sso")
public class SSOController {

	Logger log = LoggerFactory.getLogger(SSOController.class);

	@Autowired
	ConfAdmin conf;

	@Autowired
	AuthTokenService authTokenService;
	
	@Autowired
	TenantManService tenantManService;


	private String uasCamURL;
	private String gotoURL;
	private String lspURL;

	@PostConstruct
	public void init() {

		StringBuilder uasCamURLBuilder = new StringBuilder();
		uasCamURLBuilder.append("http://").append(conf.uasHost).append(":").append(conf.uasPort);
		uasCamURLBuilder.append("/cam/AuthServices");
		uasCamURL = uasCamURLBuilder.toString();
		
		StringBuilder gotoURLBuilder = new StringBuilder();
		gotoURLBuilder.append("http://").append(conf.host).append(":").append(conf.port);
		gotoURLBuilder.append("/uas/sso/valid");
		gotoURL = gotoURLBuilder.toString();
		
		StringBuilder lspURLBuilder = new StringBuilder();
		lspURLBuilder.append("http://").append(conf.lspHost).append(":").append(conf.lspPort);
		lspURL = lspURLBuilder.toString();
	}

	@RequestMapping(value = "/login/{calisCode}")
	@GetMapping
	public void login(@PathVariable String calisCode, HttpServletRequest request, HttpServletResponse response)
			throws URISyntaxException, IOException {

		// TODO 验证tenantId

		URIBuilder builder = new URIBuilder(uasCamURL);
		builder.setParameter("syslogin", "0");
		builder.setParameter("code", calisCode);
		builder.setParameter("goto", gotoURL+"/"+calisCode);

		response.sendRedirect(builder.toString());

	}
	
	
	@RequestMapping(value = "/valid/{calisCode}")
	@GetMapping
	public String valid(@PathVariable String calisCode, @RequestParam Boolean authresult, @RequestParam String artifact, HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws IOException {

		SSOToken ssoToken = new SSOToken();
		if (!authresult) {
//			return new ResponseEntity<String>("authresult is false",HttpStatus.BAD_REQUEST);
			ErrorInfo errorInfo = new ErrorInfo();
			errorInfo.setStatusCode(400);
			errorInfo.setMessage("authresult is false");
			map.addAttribute("errorInfo", errorInfo);
			return "error";
		}
		
		ResponseEntity<String> rst = null;
		String okapiToken;
//		try {
//			rst = uasService.checkArtifact(artifact);
//		} catch (Exception e) {
//			return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
//		}
//		String content = rst.getBody();
//		
//		Properties prop = new Properties();
//		try {
//			prop.load(new InputStreamReader(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)),
//					StandardCharsets.UTF_8));
//		} catch (IOException e) {
//			return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
//		}
//		String loginStatus = prop.getProperty(Constant.UAS_UM_LOGINSTATUS);
//		if (!loginStatus.equals("success")) {
//			return ResponseEntity.badRequest().body("invalid artifact");
//		}
//		String organizationCode = prop.getProperty(Constant.UAS_UM_ORGANIZATION_CODE);
		
		try {
			rst = tenantManService.getTenantId(calisCode);
			if(rst.getStatusCodeValue() != 200){
//				return new ResponseEntity<String>("request '/tenantman/pub/tenants' error:"+rst.getBody(), rst.getStatusCode());
				ErrorInfo errorInfo = new ErrorInfo();
				errorInfo.setStatusCode(rst.getStatusCodeValue());
				errorInfo.setMessage("request '/tenantman/pub/tenants' error:"+rst.getBody());
				map.addAttribute("errorInfo", errorInfo);
				return "error";
			}
			String okapiTenant = rst.getBody();
			if(okapiTenant == null || okapiTenant.isEmpty()){
//				return ResponseEntity.badRequest().body("not okapi tenant matched with "+calisCode);
				ErrorInfo errorInfo = new ErrorInfo();
				errorInfo.setStatusCode(400);
				errorInfo.setMessage("not okapi tenant matched with "+calisCode);
				map.addAttribute("errorInfo", errorInfo);
				return "error";
			}
			rst = authTokenService.checkToken(artifact, okapiTenant);
			if(rst.getStatusCodeValue() != 200){
//				return new ResponseEntity<String>("request '/uas/authtoken/token' error:"+rst.getBody(), rst.getStatusCode());
				ErrorInfo errorInfo = new ErrorInfo();
				errorInfo.setStatusCode(rst.getStatusCodeValue());
				errorInfo.setMessage("request '/uas/authtoken/token' error:"+rst.getBody());
				map.addAttribute("errorInfo", errorInfo);
				return "error";
			}
			okapiToken = rst.getBody();
			map.addAttribute("okapiToken", okapiToken);
		} catch (Exception e) {
//			return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
			ErrorInfo errorInfo = new ErrorInfo();
			errorInfo.setStatusCode(500);
			errorInfo.setMessage(e.getMessage());
			map.addAttribute("errorInfo", errorInfo);
			return "error";
		}
		map.addAttribute("artifact", artifact);
		
		String url = lspURL+"/welcome.html?artifact="+artifact+"&okapiToken="+okapiToken;
		
		return "redirect:"+url;
	}

}
